<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .shadow {
            width: 200px;
            height: 200px;
            background-color: rgba(0, 0, 0, 0.4);
            /* margin: 100px; */
            /* transform: translate(); */
            /* position: absolute; */
            position: absolute;
            left: 100px;
            top: 100px;
        }

        .sub {
            width: 100px;
            height: 100px;
            background-color: #6ff;
            margin: 50px;
            pointer-events: none;
        }
    </style>
</head>

<body>
    <div class="shadow">
        <!-- <div class="sub"></div> -->
    </div>
</body>
<script>
    // 拖拽三剑客
    // onmousedown   
    // onmousemove
    // onmouseup

    var shadow = document.getElementsByClassName("shadow")[0];


    // 1. 鼠标按下时  记录按下的位置
    shadow.onmousedown = function (e) {
        var e = e || window.event;

        // b. 借助事件对象的属性
        var posX = e.offsetX;
        var posY = e.offsetY;
        console.log(posX, posY);

        // 2. 鼠标移动时  盒子跟随鼠标按下的位置移动  (先按下 再移动)
        document.onmousemove = function (e) {
            var e = e || window.event;
            var x = e.pageX - posX;
            var y = e.pageY - posY;

            shadow.style.left = x + "px";
            shadow.style.top = y + "px";
        }

        // 3.  鼠标在文档任意位置松开  => 清除移动事件
        document.onmouseup = function () {
            document.onmousemove = null;
        }

    }



</script>

</html>